'''
Created on Nov 24, 2011

@author: onetera
'''
from PyQt4 import QtCore , QtGui
from lib.customUI import customUI
from lib.papyDB import papyDB , tableInfo
from lib.papyDBTable import *
from insertItem_UI import insertItemDiag_UI
from lib.itemModel import Asset


g_assetID , g_assetName  , g_assetStatus  , g_assetType  , g_assetDesc = range(5)

class insertAssetTableModel(QtCore.QAbstractTableModel):
    
    def __init__(self):
        super(insertAssetTableModel, self).__init__()
        self.assets = []
        self.dirty = False
        
    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.TextAlignmentRole:
            if orientation == QtCore.Qt.Horizontal:
                return QtCore.QVariant(int(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter))
            return QtCore.QVariant(int(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter))
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        if orientation == QtCore.Qt.Horizontal:
            if section == g_assetID:
                return QtCore.QVariant("ID")
            elif section == g_assetName:
                return QtCore.QVariant("Name")
            elif section == g_assetStatus:
                return QtCore.QVariant("Status")
            elif section == g_assetType:
                return QtCore.QVariant("Type")           
            elif section == g_assetDesc:
                return QtCore.QVariant("Description")
        return QtCore.QVariant(int(section + 1))    
    
    def rowCount(self, index=QtCore.QModelIndex() ):
        return len( self.assets )
    
    def columnCount(self, index=QtCore.QModelIndex()):
        return 5
    
    def removeRows(self, position, rows=1, index=QtCore.QModelIndex() ):
        self.beginRemoveRows(QtCore.QModelIndex(), position, position + rows - 1)        
        self.assets = self.assets[:position] + self.assets[position + rows:]            
        self.endRemoveRows()   
        self.dirty = True     
        return True
    
         
    def data(self, index, role=QtCore.Qt.DisplayRole):
        if (not index.isValid() or
            not (0 <= index.row() < len(self.assets))):
            return QtCore.QVariant()   
        iASSET = self.assets[ index.row() ]
        column = index.column()        
        if role == QtCore.Qt.DisplayRole:
            if column == g_assetID:
                return QtCore.QVariant(iASSET.assetID)
            elif column == g_assetName:
                return QtCore.QVariant(iASSET.assetName)
            elif column == g_assetStatus:
                return QtCore.QVariant(iASSET.assetStatus)
            elif column == g_assetType:
                return QtCore.QVariant(iASSET.assetType)            
            elif column == g_assetDesc:
                return QtCore.QVariant(iASSET.assetDesc)
        return QtCore.QVariant()
    

class insertItemDiag(insertItemDiag_UI  ): 
    def __init__(self ,  parent=None ):
        insertItemDiag_UI.__init__(self,parent  )
    
    def setcbIndex(self , pssd ):
        self.iprj , self.iseq , self.ishot = pssd[0][1] , pssd[1][1] , pssd[2][1]
        
    def showDiag( self ):
        self.setUI()
        self.initPrj()
        self.prj_cb.insertItem( 0 , '--All--')
        self.initDept()
        self.prj_cb.currentIndexChanged.connect( self.initSeqM )
        self.seq_cb.currentIndexChanged.connect( self.initShotG )        
        self.insertAssetTableModel = insertAssetTableModel()        
        self.asset_table.setModel( self.insertAssetTableModel )
        self.tagSearch_btn.clicked.connect( self.initialModel )
        self.initSeqM()
        self.initShotG()       
        
        self.dept_cb.removeItem(self.dept_cb.findText('Animation') )
        self.dept_cb.removeItem(self.dept_cb.findText('Comp') )
        self.dept_cb.removeItem(self.dept_cb.findText('FX') )
        self.dept_cb.removeItem(self.dept_cb.findText('Layout') )
        self.dept_cb.removeItem(self.dept_cb.findText('Lighting') )
        self.dept_cb.removeItem(self.dept_cb.findText('Render') )
        self.dept_cb.removeItem(self.dept_cb.findText('TD') )
        
        self.show()
        
        
#        iprj = [ str( self.prj_cb.itemText(x) ) for x in range( self.prj_cb.count() ) ].index(self.iprj) if self.iprj != '' else 0        
#        self.prj_cb.setCurrentIndex(iprj)
#        iseq = [ self.seq_cb.itemText(x) for x in range( self.seq_cb.count() ) ].index(self.iseq) if self.iseq != '' else 0
#        self.seq_cb.setCurrentIndex(iseq)
#        ishot = [ self.shot_cb.itemText(x) for x in range( self.shot_cb.count() ) ].index(self.ishot) if self.ishot != '' else 0
#        self.shot_cb.setCurrentIndex(ishot)
#        self.initialModel()
    
    def refreshAssetTable(self):
        self.searchAsset()
    
    def searchAsset(self):
        prj = str( self.prj_cb.currentText() )
        seq = str( self.seq_cb.currentText() )
        shot = str( self.shot_cb.currentText() )
        dept = str( self.dept_cb.currentText() )
        tags =  str( self.tag_lineEdt.text() ).split(',') if str( self.tag_lineEdt.text() ) != '' else ''
#        print prj , seq , shot , dept , tags
        queryDic = {'prj':prj,'seq':seq,'shot':shot,'dept':dept,'tags':tags}
        
        column = "select distinct ASSET.assetID "   
        tables = "from ASSET "    
        query = ""
        
        if shot != '--Global--' :
#            print "SHOT_has_ASSET"
            tables += ", SHOT, SHOT_has_ASSET "
            query += " where ASSET.assetID=SHOT_has_ASSET.assetID and SHOT.shotID=SHOT_has_ASSET.shotID and SHOT.shotName='%(shot)s' "
        if seq != '--Master--' and shot == '--Global--' :
#            print "SEQUENCE_has_ASSET"
            tables += ", SEQUENCES, SEQUENCES_has_ASSET "
            query += " where ASSET.assetID=SEQUENCES_has_ASSET.assetID and SEQUENCES.seqID=SEQUENCES_has_ASSET.seqID and SEQUENCES.seqName='%(seq)s' "
        if prj != '--All--' and seq == '--Master--' and shot == '--Global--' :
#            print "PROJECT_has_ASSET"
            tables += ", PROJECT, PROJECT_has_ASSET "
            query += " where ASSET.assetID=PROJECT_has_ASSET.assetID and PROJECT.prjID=PROJECT_has_ASSET.prjID and PROJECT.prjCodeName='%(prj)s' "
        if prj == '--All--' and seq == '--Master--' and shot == '--Global--' :
            tagSearch = 1
                
        if tags != '' :
            tables += ", ASSET_TAG, ASSET_has_ASSET_TAG "
            if tagSearch != 1 :
                query += " and ASSET.assetID=ASSET_has_ASSET_TAG.assetID and ASSET_TAG.assetTagID=ASSET_has_ASSET_TAG.assetTagID "
            else :
                query += " where ASSET.assetID=ASSET_has_ASSET_TAG.assetID and ASSET_TAG.assetTagID=ASSET_has_ASSET_TAG.assetTagID "
            for x in queryDic['tags'] :
                query += " and ASSET_TAG.Tag = '%s'" % x   
        query = query % queryDic
        query = column+tables+query
        result= list ( papyDB.getFetch(query) )
        assetID = []        
        for x in range( len(papyDB.getFetch(query)) ) :
            assetID.append( papyDB.getFetch(query)[x][0] )
        deptID = DEPARTMENT.search('deptID' , deptName=dept)
        
        result2 = ()
        for x in range( len(assetID) ) :
            query = "select distinct ASSET_JOB.ID, ASSET.assetName, ASSET_JOB.status, ASSET.assetType, ASSET_JOB.description "
            query += " from ASSET_JOB, ASSET "
            query += " where ASSET_JOB.assetID='%s' and ASSET_JOB.deptID='%s' and ASSET_JOB.assetID=ASSET.assetID" % (int(assetID[x]), int(deptID))
            result2 += papyDB.getFetch(query)
        
        self.aPath = queryDic
#        print self.aPath
        
        return result2
        
        
        
    def generateModelList(self  ):
        for assetID , assetName  ,  assetStatus , assetType  ,   assetDesc in self.searchAsset() :
            yield Asset(assetID , assetName  ,  assetStatus  ,  assetType  ,   assetDesc )
    
    
    
    def getAssetVer(self, asset):  
#        print  "asset.assetVersion",papyDBTable.ASSET_VERSION.search('assetVer' , assetID = asset.assetID )
        theList = ASSET_VERSION.search('assetVer' , assetID = asset.assetID )        
        if type( theList ) != type( [] ) or not len( theList ) :
            theList = [ theList ]  
        theList.reverse()      
        return theList
             
    def initialModel( self ):
        if self.insertAssetTableModel.rowCount() > 0:   
            for x in range( self.insertAssetTableModel.rowCount() ):    
                self.insertAssetTableModel.removeRows( 0 ) 
        for x in self.generateModelList():
            
            x.assetVersionList = self.getAssetVer( x )
            x.assetVersion = str( x.assetVersionList[ 0 ] ).zfill(3)
            self.insertAssetTableModel.assets.append( x )
        self.insertAssetTableModel.reset()
        self.asset_table.resizeColumnsToContents()
#        self.asset_table.resizeColumnToContents(6)
        self.asset_table.setColumnWidth(1,150)
        self.asset_table.setColumnWidth(4,200)
#        print self.insertAssetTableModel
        
    def initSeqM(self):
        self.initSeq('--Master--')
        
    def initShotG(self):
        self.initShot('--Global--')
 


            
if __name__ == '__main__':
    import sys    
    app = QtGui.QApplication(sys.argv)     
    ui = insertItemDiag()
    ui.setcbIndex( [[0, 0], [0, 0], [0, 0], [0, 0], [[1, 26, 31, 36, 41, 46, 51], 'onetera']] )
    ui.showDiag()   
    app.exec_()           